<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const sources = {
        npm: {
          registry: 'https://registry.npmjs.org/'
        },
        yarn: {
          registry: 'https://registry.yarnpkg.com/'
        },
        tencent: {
          registry: 'https://mirrors.cloud.tencent.com/npm/'
        },
        cnpm: {
          registry: 'https://r.cnpmjs.org/'
        },
        taobao: {
          registry: 'https://registry.npmmirror.com/'
        },
        npmMirror: {
          registry: 'https://skimdb.npmjs.com/registry/'
        }
      }

      // 创建一个函数来检查一个源的响应速度
      function checkSourceSpeed(source) {
        return new Promise((resolve, reject) => {
          const startTime = Date.now()
          fetch(source.registry, { method: 'HEAD' })
            .then((response) => {
              const endTime = Date.now()
              const duration = endTime - startTime
              resolve({ sourceName: source.name, duration })
            })
            .catch((error) => {
              reject(error)
            })
        })
      }

      // 为每个源创建一个Promise
      const promises = Object.keys(sources).map((sourceName) => {
        const source = sources[sourceName]
        return checkSourceSpeed(source).catch((error) => {
          console.error(`Error checking ${sourceName} source:`, error)
          return { sourceName, duration: Infinity } // 如果出错，则设定一个非常大的持续时间
        })
      })

      // 使用Promise.race找出哪个源最快
      Promise.race(promises)
        .then((fastestSource) => {
          console.log(`The fastest source is ${fastestSource.sourceName} with a duration of ${fastestSource.duration}ms.`)
        })
        .catch((error) => {
          console.error('An error occurred during the source speed check:', error)
        })
    </script>
  </body>
</html>
